package guoanmaker.operator.business.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;

import guoanmaker.operator.business.model.OperatorApkPath;
import guoanmaker.operator.business.repository.OperatorApkPathRepository;
import guoanmaker.operator.business.service.OperatorApkServiceInterface;
import guoanmaker.operator.helper.common.AjaxJson;
import guoanmaker.operator.helper.common.abstractobj.ApiController;
import guoanmaker.operator.helper.common.util.OSSUnitHelper;
import io.swagger.annotations.ApiOperation;

/**
 * 
* @ClassName: OperatorApkController.java 
* @Description: 评价controller
* @author Cancerl
* @date 2018年4月12日
*  
 */
@RestController
@RequestMapping(ApiController.APK_MANMAGER_URL)
public class OperatorApkController {
	
	@Autowired
	private OperatorApkServiceInterface operatorApkService;
	
	@Autowired
	private OperatorApkPathRepository apkPathRepository;
	
	@ApiOperation(value="上传",notes="上传")
	@PostMapping("/putApk")
	public AjaxJson putImg(MultipartFile contractlogo , HttpServletResponse response){
		AjaxJson ajaxJson=new AjaxJson();
		if(contractlogo!=null){
			OSSUnitHelper ossunit=new OSSUnitHelper();
			OSSClient client=OSSUnitHelper.getOSSClient();
			String diskName = "datas/contractImg/";
			String fileName = new Date().getTime() + (int) ((Math.random() * 9 + 1) * 100000)
					+ contractlogo.getOriginalFilename().substring(contractlogo.getOriginalFilename().indexOf("."));
	        String md5key = OSSUnitHelper.uploadObject2OSS(client, contractlogo, diskName,fileName);
	        String url="";
	        url=OSSUnitHelper.getUrl(client, diskName, fileName);
	        String urll=    url.substring(4, url.length());
	        url="https"+urll;
	        //保存apk路径
	        OperatorApkPath apkPath = null;
	        List<OperatorApkPath> apks = apkPathRepository.findAll();
	        if(apks != null && apks.size() > 0){
	        	apkPath = apks.get(0);
	        }else{
	        	apkPath = new OperatorApkPath();
	        }
	        apkPath.setUrl(url);
	        apkPathRepository.save(apkPath);
	        System.out.println(url+"5");
	        if(url!=null&&!url.equals("")){
	        	ajaxJson.setSuccess(true).setStatus(200).setData(url);
	        	response.setContentType(url);
	        } 
		 }
		 return ajaxJson;
	}
	
	@ApiOperation(value="下载",notes="下载")
	@GetMapping("/downloadApk")
	public void getAllContractDownloadCounts(HttpServletResponse response){
		operatorApkService.downloadFile(response);
	}
}
